<template>
  <div>
    <Layout>
      <template #search>
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          :v-show="true"
          label-width="68px"
        >
          <el-form-item label="素材标题" prop="materialTitle">
            <el-input
              v-model="queryParams.materialTitle"
              placeholder="请输入素材标题"
              style="width: 200px; height: 32px"
              @change="handleQuery"
              clearable
            />
          </el-form-item>
          <el-form-item label="素材类型" prop="materialType">
            <InputSelect
              text="请输入素材类型"
              :modelValue="queryParams.materialType"
              :options="materialType"
              @update:modelValue="materialTypeSearch"
            />
          </el-form-item>
          <el-form-item label="素材格式类型" prop="materialFormatType">
            <InputSelect
              text="请输入素材格式类型"
              :modelValue="queryParams.materialFormatType"
              :options="materialFormat"
              @update:modelValue="materialFormatTypeSearch"
            />
          </el-form-item>
          <el-form-item label="素材内容摘要" prop="materialSummary">
            <el-input
              v-model="queryParams.materialSummary"
              placeholder="请输入素材内容摘要"
              clearable
              style="width: 200px; height: 32px"
              @change="handleQuery"
            />
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus">
            <InputSelect
              text="请输入审核状态"
              :modelValue="queryParams.auditStatus"
              :options="queryData.auditStatusList"
              @update:modelValue="auditStatusSearch"
            />
          </el-form-item>
          <el-form-item label="展示状态" prop="showState">
            <InputSelect
              text="请输入展示状态"
              :modelValue="queryParams.showState"
              :options="queryData.showStateList"
              @update:modelValue="showStateSearch"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              :disabled="multiple"
              @click="handleExport"
              >导出
            </el-button>
          </el-col>
        </el-row>
      </template>

      <template #content>
        <el-table :data="tableList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            prop="materialId"
            label="素材编号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="materialUrl"
            label="素材"
            align="center"
            width="150px"
          >
            <template #default="scope">
              <FilePreview-table :src="scope.row.materialUrl" fit="cover">
              </FilePreview-table>
            </template>
          </el-table-column>
          <el-table-column
            prop="materialTitle"
            label="素材标题"
            align="center"
          ></el-table-column>
          <!-- <el-table-column
            prop="materialType"
            label="素材类型"
            align="center"
          ></el-table-column> -->
          <el-table-column
            prop="typeName"
            label="素材类型"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="thumbnailUrl"
            label="封面"
            align="center"
            width="100px"
          >
            <template #default="scope">
              <ImagePreview
                :src="scope.row.thumbnailUrl"
                :width="80"
                :height="80"
                fit="cover"
              />
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="materialFormatType"
            label="素材格式类型"
            align="center"
          ></el-table-column> -->
          <el-table-column prop="materialTags" label="标签" align="center">
            <template #default="scope">
              <TableTag :dynamicTags="scope.row.materialTags"></TableTag>
            </template>
          </el-table-column>
          <el-table-column prop="auditStatus" label="审核状态" align="center">
            <template #default="scope">
              <el-tag v-show="scope.row.auditStatus == 0" effect="dark" round>
                未通过</el-tag
              >
              <el-tag v-show="scope.row.auditStatus == 1" effect="dark" round>
                审核中</el-tag
              >
              <el-tag v-show="scope.row.auditStatus == 2" effect="dark" round>
                已通过</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="fileSize"
            label="文件大小（KB）"
            :formatter="fileSizeFormatter"
            align="center"
          ></el-table-column>
          <el-table-column prop="showState" label="展示状态" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.showState"
                inline-prompt
                :inactive-value="1"
                inactive-text="未展示"
                :active-value="0"
                active-text="正常展示"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="publishTime"
            label="发布时间"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="collectionCount"
            label="收藏数"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="remark"
            label="备注信息"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >修改
              </el-button>
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getPageList"
        />
        <!-- 添加或修改对话框 -->
        <Dialog
          :show="dialogConfig.show"
          :title="dialogConfig.title"
          :buttons="dialogConfig.buttons"
          width="600px"
          :showCancel="false"
          @close="clear"
          :showClose="false"
          :closeOnClickModal="true"
        >
          <el-form
            ref="dialogFormRef"
            :model="form"
            :rules="rules"
            label-width="80px"
            label-position="left"
            inline
          >
            <!-- 文件预览 -->
            <el-form-item label="文件预览" prop="materialUrl">
              <FilePreviewDialog :src="form.materialUrl"> </FilePreviewDialog>
            </el-form-item>
            <el-form-item label="素材存储地址" prop="materialUrl">
              <FileUpload @file="getFilePath"> </FileUpload>
            </el-form-item>
            <el-form-item label="素材标题" prop="materialTitle">
              <el-input
                v-model="form.materialTitle"
                placeholder="请输入素材标题"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="素材类型" prop="materialType">
              <InputSelect
                text="请选择素材类型"
                :modelValue="form.materialType"
                :options="materialType"
                @update:modelValue="handlematerialTypeChange"
              />
            </el-form-item>
            <el-form-item label="缩略图路径" prop="thumbnailUrl">
              <ImageUpload
                :imageUrl="form.thumbnailUrl"
                ref="uploadRef"
                @filePath="getImgPath"
              />
            </el-form-item>
            <el-form-item label="素材格式类型" prop="materialFormatType">
              <InputSelect
                text="请选择素材格式类型"
                :modelValue="form.materialFormatType"
                :options="materialFormat"
                @update:modelValue="handlematerialFormatTypeChange"
              />
            </el-form-item>
            <el-form-item
              label="素材内容摘要"
              prop="materialSummary"
              style="height: 100px"
            >
              <el-input
                v-model="form.materialSummary"
                placeholder="请输入素材内容摘要"
                style="width: 300px"
                type="textarea"
                clearable
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>
            <el-form-item label="标签" prop="materialTags">
              <SimpleTag
                :dynamicTags="form.materialTags"
                @addTag="handleAddTag"
              >
              </SimpleTag>
            </el-form-item>

            <el-form-item label="审核状态" prop="auditStatus">
              <InputSelect
                text="请输入审核状态"
                :modelValue="form.auditStatus"
                :options="queryData.auditStatusList"
                @update:modelValue="handleAuditStatusChange"
              />
            </el-form-item>
            <el-form-item label="文件大小（KB）" prop="fileSize">
              <el-input
                v-model="form.fileSize"
                placeholder="请输入文件大小"
                style="width: 200px; height: 32px"
                clearable
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="收藏数" prop="collectionsCount">
              <el-input
                v-model="form.collectionCount"
                placeholder="收藏数"
                style="width: 200px; height: 32px"
                clearable
                disabled
              ></el-input>
            </el-form-item>

            <el-form-item label="删除标记" prop="delFlag">
              <template #default>
                <el-switch
                  v-model="form.delFlag"
                  inline-prompt
                  active-text="正常使用"
                  :active-value="0"
                  :inactive-value="1"
                  inactive-text="已删除"
                />
              </template>
            </el-form-item>

            <el-form-item label="展示状态" prop="showState">
              <template #default>
                <el-switch
                  v-model="form.showState"
                  inline-prompt
                  active-text="展示中"
                  :active-value="0"
                  :inactive-value="1"
                  inactive-text="未展示"
                />
              </template>
            </el-form-item>
            <el-form-item label="发布时间" prop="publishTime">
              <el-date-picker
                type="datetime"
                placeholder="发布时间"
                v-model="form.publishTime"
                disabled
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                type="datetime"
                placeholder="创建时间"
                v-model="form.createTime"
                disabled
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                type="datetime"
                placeholder="更新时间"
                v-model="form.updateTime"
                disabled
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="创建人" prop="createBy">
              <el-input
                v-model="form.createBy"
                placeholder="请输入创建人"
                style="width: 200px; height: 32px"
                clearable
                disabled
              ></el-input>
            </el-form-item>

            <el-form-item label="更新人" prop="updateBy">
              <el-input
                v-model="form.updateBy"
                placeholder="请输入更新人"
                style="width: 200px; height: 32px"
                clearable
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="备注信息" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入备注信息"
                style="width: 200px; height: 32px"
                clearable
              ></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </Dialog>
      </template>
    </Layout>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  computed,
  onMounted,
  provide,
  toRefs,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout/Layout-common.vue";
import {
  getMaterialList,
  getMaterialById,
  addMaterial,
  updateMaterial,
  deleteMaterial,
  deleteMaterialBatch,
} from "@/api/material.js";
import { getMaterialTypeNameList } from "@/api/page/classify.js";
import { download } from "@/utils/request.js";
import { deleteOssFile } from "@/api/page/home.js";
import Dialog from "@/components/Dialog.vue";
import FilePreviewDialog from "@/components/FilePreview/dialog.vue";

// 分页数据
const total = ref(0);
// 用户数据
const tableList = ref([]);
// 用户选择项
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 定义 queryFormRef
const queryFormRef = ref(null);
// 搜索查询数据
const queryData = reactive({
  // 搜索栏的数据
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  // 搜索栏的表单校验规则
  queryRules: {},
  // 审核状态
  auditStatusList: [
    { name: "未通过", value: "0" },
    { name: "审核中", value: "1" },
    { name: "已通过", value: "2" },
  ],
  // 展示状态
  showStateList: [
    { name: "展示中", value: "0" },
    { name: "未展示", value: "1" },
  ],
  // 素材类型
  materialTypeList: [],
});
const { queryParams, queryRules, materialTypeList } = toRefs(queryData);

// 弹窗的表单数据
const formData = reactive({
  // 修改、新增弹窗表单数据
  form: {},
  rules: {
    materialTitle: [
      { required: true, message: "请输入素材名称", trigger: "blur" },
      { min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur" },
    ],
    materialType: [
      { required: true, message: "请选择素材类型", trigger: "blur" },
    ],
  },
  // 需要删除的文件数组（删除之前存储的文件）
  imgData: [],
  // 文件素材数组(用于删除旧数据)
  fileData: [],
  // 用于记录上传的文件数据
  fileList: [],
});
// 修改、新增弹窗表单数据
const dialogFormRef = ref();
// 上传组件的ref
const uploadRef = ref();
// 结构属性，转为ref
const { form, rules, imgData, fileData, fileList } = toRefs(formData);

// 弹窗相关参数
const dialogConfig = reactive({
  show: false,
  title: "",
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

// 使用 computed 缓存处理后的素材类型List
const materialType = computed(() => {
  return materialTypeList.value.map((item) => {
    return {
      name: item.typeName,
      value: item.typeId,
    };
  });
});

// 素材格式类型
const materialFormat = computed(() => {
  return [
    { name: "png", value: "png" },
    { name: "jpg", value: "jpg" },
    { name: "jpeg", value: "jpeg" },
    { name: "mp4", value: "mp4" },
    { name: "mp3", value: "mp3" },
    { name: "xlsx", value: "xlsx" },
    { name: "xls", value: "xls" },
    { name: "pdf", value: "pdf" },
    { name: "docx", value: "docx" },
    { name: "doc", value: "doc" },
    { name: "webp", value: "webp" },
    { name: "gif", value: "gif" },
  ];
});

onMounted(() => {
  getPageList();
  // 获取所有素材类型数据
  getMaterialType();
});

// 搜索栏的查询
const handleQuery = () => {
  console.log("queryParams", queryParams.value);
  getPageList();
};

// 素材标题的

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
  };
  getPageList();
};

// 批量操作
const handleSelectionChange = (val) => {
  ids.value = val.map((item) => item.materialId);
  single.value = val.length != 1;
  multiple.value = !val.length;
  console.log("ids:", ids.value);
};

// 导出数据
const handleExport = () => {
  // 发送请求
  download(
    "/Material/export",
    ids.value,
    `素材信息_${new Date().getTime()}.xlsx`
  );
};

// 获取所有数据
function getPageList() {
  getMaterialList(queryParams.value).then((response) => {
    tableList.value = response.rows;
    // console.log("tableList:", tableList.value);
    total.value = response.total;
  });
}

// 获取素材类型数据
function getMaterialType() {
  getMaterialTypeNameList().then((response) => {
    materialTypeList.value = response.data;
    // console.log("materialTypeList:", materialTypeList.value);
  });
}

// 弹窗表单重置
function reset() {
  form.value = {
    materialUrl: null,
    materialTitle: null,
    materialType: null,
    thumbnailUrl: null,
    materialFormatType: null,
    materialSummary: null,
    materialTags: null,
    auditStatus: null,
    fileSize: null,
    delFlag: null,
    showState: null,
    publishTime: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    collectionsCount: null,
    updateBy: null,
    remark: null,
  };
  formData.fileList = [];
}

// 搜索-素材类型的下拉菜单
const materialTypeSearch = (val) => {
  queryParams.value.materialType = val;
};
// 搜索-素材格式类型的下拉菜单
const materialFormatTypeSearch = (val) => {
  queryParams.value.materialFormatType = val;
};
// 搜索-审核状态的下拉菜单
const auditStatusSearch = (val) => {
  queryParams.value.auditStatus = val;
};
// 搜索-展示状态的下拉菜单
const showStateSearch = (val) => {
  queryParams.value.showState = val;
};

// 弹窗表单-素材类型的下拉菜单
const handlematerialTypeChange = (val) => {
  form.value.materialType = val;
};
// 弹窗表单-审核状态的下拉菜单
const handleAuditStatusChange = (val) => {
  form.value.auditStatus = val;
};
// 弹窗表单-素材格式类型的下拉菜单
const handlematerialFormatTypeChange = (val) => {
  form.value.materialFormatType = val;
};

/** 新增按钮操作 */
function handleAdd() {
  dialogConfig.show = true;
  dialogConfig.title = "添加素材信息";
  reset();
}

// 修改按钮操作
function handleUpdate(row) {
  const materialId = row.materialId || ids.value;
  getMaterialById(materialId).then((response) => {
    form.value = response.data;
    //
    dialogConfig.show = true;
    dialogConfig.title = "修改素材信息";
  });
}

//  删除按钮操作
const handleDelete = (row) => {
  // 判断参数ids是否有值
  // 有,则执行删除多个操作
  if (ids.value.length > 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      deleteMaterialBatch(ids.value)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getPageList();
      }, 200);
    });
  }
  if (ids.value.length == 0) {
    ElMessageBox.confirm("是否确认删除", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(function () {
      console.log("row:", row);
      // 删除操作
      deleteMaterial(row.materialId)
        .then((result) => {
          if (result.code == 200) {
            ElMessage.success("删除成功");
          }
          if (result.code == 500) {
            ElMessage.error("删除失败");
          }
        })
        .catch((err) => {
          ElMessage.error("删除失败");
        });
      // 重新获取数据
      setTimeout(() => {
        getPageList();
      }, 200);
    });
  }
};

// 弹框确认  修改/添加
const submitForm = () => {
  // 修改操作
  if (dialogConfig.title == "修改素材信息") {
    // 上传新的图片，获取数据
    updateMaterial(form.value)
      .then((result) => {
        if (result.code == 200) {
          ElMessage.success("修改成功");
          // 重新获取数据
          setTimeout(() => {
            getPageList();
          }, 200);
          dialogConfig.show = false;
          setTimeout(() => {
            dialogFormRef.value.resetFields();
          }, 300);
        }
      })
      .catch((err) => {
        ElMessage.error("修改失败");
      });
  }

  // 添加操作
  else if (dialogConfig.title == "添加素材信息") {
    // 校验表单参数，是否填写
    form.value.delFlag = 0;
    dialogFormRef.value.validateField(
      ["materialTitle", "materialType"],
      (errors) => {
        //通过校验
        if (errors) {
          // 判断用户是否上传了文件
          if (form.value.materialUrl == null || form.value.materialUrl == "") {
            ElMessage.error("请上传文件");
            return;
          }

          if (Array.isArray(form.value.materialUrl)) {
            // 转换为json字符串
            form.value.materialUrl = JSON.stringify(form.value.materialUrl);
          }
          addMaterial(form.value)
            .then((result) => {
              if (result.code == 200) {
                ElMessage.success("添加成功");
                // 重新获取数据
                setTimeout(() => {
                  getPageList();
                }, 200);
                dialogConfig.show = false;
                setTimeout(() => {
                  dialogFormRef.value.resetFields();
                }, 300);
              }
            })
            .catch((err) => {});
        } else {
          ElMessage.error("请填写必填项");
        }
      }
    );
  }
};

// 数据还原
const clear = () => {
  // 清除上传子组件的文件列表和img
  imgData.value = [];
  fileData.value = [];
  fileList.value = [];
  uploadRef.value.clearFileList();
  dialogConfig.show = false;
  setTimeout(() => {
    reset();
  }, 300);
};

// 弹窗表单上传组件功能
const getImgPath = (filePath) => {
  // 上传文件之前，把前一个文件路径，记录下来
  // 获取文件名 保存之前的文件的路径，便于删除
  if (form.value.thumbnailUrl) {
    let fileName = form.value.thumbnailUrl?.split("/").pop() || "";
    imgData.value.push(fileName);
  }

  //   修改form的属性值
  form.value.thumbnailUrl = filePath;
};

// 获取素材文件地址
const getFilePath = (files) => {
  // 将 size 转换为数值类型
  console.log("files:", files);

  // 清除旧数据（避免重复提交）
  formData.fileList = [];
  form.value.materialUrl = [];
  form.value.fileSize = 0;

  // 收集所有文件信息
  files.forEach((file) => {
    const fileSize = parseFloat(file.size);
    if (isNaN(fileSize)) {
      ElMessage.error("文件大小格式错误");
      return;
    }
    formData.fileList.push({ ...file, size: fileSize });
  });

  // 计算总大小（单位：KB）
  const totalSize = formData.fileList.reduce((sum, item) => sum + item.size, 0);
  form.value.fileSize = totalSize.toFixed(2);

  // 素材地址使用fileList数组中每个文件的url属性组成一个新数组
  // 设置素材地址为URL数组
  form.value.materialUrl = formData.fileList.map((item) => item.url);

  // 根据第一个文件设置格式类型和缩略图
  const firstFile = formData.fileList[0];
  if (firstFile) {
    const format = firstFile.url.split(".").pop().toLowerCase();
    form.value.materialFormatType = format;

    // 设置缩略图（仅当是图片时）
    if (["jpg", "png", "jpeg", "webp", "gif"].includes(format)) {
      form.value.thumbnailUrl = firstFile.url;
    }
  }

  // 当上传的素材为音频或者素材时
  if (
    ["mp3", "wav", "ogg", "aac"].includes(form.value.materialFormatType) ||
    ["mp4", "avi", "mov", "webm", "mkv"].includes(form.value.materialFormatType)
  ) {
    // 将文件预览组件的值传入，之前已经写入
    // form.value.materialUrl = firstFile.url;
  }
};

// 获取标签属性
const handleAddTag = (val) => {
  console.log("tags:", val);
  form.value.materialTags = val;
};

// 表格文件大小格式
const fileSizeFormatter = (row, column, value) => {
  return value.toFixed(2) + " KB"; // 保留两位小数
};
</script>

<style lang="scss" scoped>
/* 确保 el-form-item 高度自适应 */
</style>
